<template>
  <div>
    <Button type="info" class="choose-btn" v-if="showChooseBtn" @click="showDrawer">选择</Button>
    <Upload
        id="fileID"
        :show-upload-list='showUploadList'
        :on-success="getFileUrl"
        :default-file-list="defaultList"
        :headers="uploadHeader"
        :on-remove = "clearFileInList"
        :data="uploadParams"
        :accept="accept"
        ref='uploadFile' :action="`${uploadAction}?visibility=company&bucket=${fileType !== 'glb' ? fileType : 'relay'}&type=${fileType}`" :before-upload="handleUploadIcon">
        <Button icon="ios-cloud-upload-outline" :disabled="loading">{{uploadText}}</Button>
    </Upload>
    <div v-if="showUploadList&&fileType=='images'&&(file.filePath&&file.filePath!=-1)" class="imageShow">
        <img :src="`/Learn${this.file.filePath}`"
                style="width:auto;height:40px;vertical-align: middle;"/>
        <Icon type="ios-close" class="imageDelIcon" @click.native="clearFileInList" />
    </div>
    <Tooltip style="position: absolute; top: 0;" :style="{'left': `${iconLeft ? iconLeft : showChooseBtn ? 178 : 118}px`}" :transfer='true' max-width="200" placement="top">
        <Icon type="ios-alert" class="ios-alert" style="color: rgb(255, 153, 0);" />
        <div class="api" slot="content">
            <p style="white-space: normal;word-break: break-all;">支持上传类型:{{formatArr && formatArr.toString()}}</p>
            <p style="white-space: normal;">文件名称:只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符</p>
        </div>
    </Tooltip>
    <div class="file-list">
        <div v-for="item in selfFileList" :key="item.id" class="content">
            <template v-if="fileType !== 'images' || noPath">
                <Icon :type="fileType === 'docs' ? 'ios-document' : fileType === 'videos' ? 'ios-videocam' : 'logo-dropbox'" :size="16"/>
                <div class="file-name">{{item.fileName}}</div>
                <Poptip
                    trigger="click"
                    confirm
                    title="确认删除吗？"
                    @on-ok="delItem(item.id)">
                    <Button icon="ios-trash"></Button>
                </Poptip>
            </template>
            <template v-else>
                <img :src="`/Learn${item.path}`"
                    style="width:auto;height:40px;vertical-align: middle;"/>
                <Poptip
                    trigger="click"
                    confirm
                    title="确认删除吗？"
                    @on-ok="delImge(item.path)">
                    <Button icon="ios-trash"></Button>
                </Poptip>
            </template>
        </div>
    </div>
    <Drawer :title="`请选择${fileTypeName}`" width="1000" v-model="drawerValue">
        <div style="display: flex;justify-content: space-between;margin-bottom: 20px">
            <div style="font-size: 14px;font-weight: bold">{{fileTypeName}}</div>
            <div>
                <Input v-model.trim="originName" :placeholder="`${fileTypeName}名称`" style="width: 180px;" clearable @on-change="getMinioList(1)" />
                <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refresh"><i class="el-icon-refresh-right" /></Button>
            </div>
        </div>
        <div>
            <Table border :columns="getShowColumns()" :data="list" :loading="loadingList"></Table>
            <div style="display: flex;justify-content: center;margin: 15px 0">
                <Page :total='total' :page-size="query.pageSize" :current="query.pageIndex" show-total show-elevator @on-change="getMinioList" />
            </div>
        </div>
    </Drawer>
  </div>
</template>

<script>
import { getFilesData } from '@/api/uploadFile.js'
import $ from 'jquery'

export default {
    props: {
        uploadParams:{
            type:Object,
            default:null
        },
        customApi:{
            type:Function,
        },
        cusdomCallback:{
            type:Function,
        },
        cusdomPassObj:{
            type:Object,
            default:null
        },
        uploadText:{
            type:String,
            default: '上传文件'
        },
        showChooseBtn: {
            type: Boolean,
            default: false
        },
        formatArr: {
            type: Array,
            default: () => []
        },
        showInfo:{
            type: Boolean,
            default: false
        },
        showUploadList: {
            type: Boolean,
            default: false
        },
        fileType: {
            type: String,
            default: 'files'
        },
        fileList: {
            type: Array,
            default: () => []
        },
        isSingle: {
            type: Boolean,
            default: false
        },
        iconLeft: {
            type: Number,
            default: 0
        },
        noPath: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        fileTypeName() {
            switch(this.fileType) {
                case 'docs': return '文档'
                case 'videos': return '视频'
                case 'files': return '工具'
                case 'images': return '图片'
            }
        },
        filePaths() {
            return this.selfFileList.map(item => item.path)
        },
        accept() {
            return this.formatArr.length ? this.formatArr.map(item => `.${item}`).join(',') : ''
        }
    },
    watch: {
        fileList(list) {
            this.selfFileList = [].concat(list)
        },
    },
    mounted() {
        this.selfFileList = [].concat(this.fileList)
        this.setStyle()
        window.addEventListener('resize', this.setStyle)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setStyle)
    },
    data() {
        return {
            otherData:[],
            USER_ID: '',
            file:{},
            defaultList:[],
            columns: [{
					title: '名称',
					key: 'originName',
					align: 'center',
                    tooltip: true
				}, {
					title: '缩略图',
					key: 'path',
					align: 'center',
					render: (h, params) => {
						return h('img', {
							attrs: {
								src: this.handleImage(params.row.path)
							},
							style: {
								display: 'inline-block',
								maxHeight: '40px',
								width: 'auto',
								verticalAlign: 'middle'
							}
						})
					}
				},
				{
					title: '可见范围',
					key: 'visibility',
					width: 100,
					align: 'center',
					render: (h, params) => {
						return h('div', {
							style: {
								color: this.handlePublic(params.row.visibility).color
							}
						}, this.handlePublic(params.row.visibility).text)
					}
				},{
					title: '内容',
					key: 'check',
					align: 'center',
					width: 100,
					render: (h, params) => {
						return h('div', [
							h('a', {
								on: {
									click: () => {
										this.checkInfo(params);
									}
								}
							}, '查看')
						]);
					}
				}, {
					title: '创建者',
					key: 'creatorName',
					align: 'center',
                    tooltip: true
				}, {
					title: '创建时间',
					key: 'created',
					align: 'center',
                    tooltip: true
				}, {
					title: '操作',
					key: 'action',
					width: 100,
					align: 'center',
					render: (h, params) => {
						let text = ''
						if(params.row.isUsed) {
							text = '已用'
						} else {
							text = '使用'
						}
						return h('a', {
							style: {
								color: params.row.isUsed ? '#2f70ff' : 'grey',
								cursor: 'pointer'
							},
						}, [
							h('div', {
								on: {
									'click': () => {
										this.chooseImg(params)
									},
								},
							}, [
								h('img', {
									attrs: {
										src: params.row.isUsed ? require('@/assets/globalIcon/choosed.png') : require('@/assets/globalIcon/add.png'),
									},
									style: {
										'margin-right': '5px',
										'vertical-align': 'middle',
										width: '16px',
										height: '16px',
										display: 'inline-block',
									},
								}),
								h('span', {}, text)
							])
						])
					}
				},
            ],
            loadingList: false,
            drawerValue: false,
            query: {
                pageIndex: 1,
                pageSize: 10
            },
            list: [],
            total: 0,
            originName: '',
            uploadHeader: {
                Authorization: localStorage.token,
                Accept: '*/*'
            },
            selfFileList: [],
            speed: 0,
            loaded: 0,
            progress: 0,
            fileSize:0,
            loading:false,
            isUpdataing:false, //判断是否在上传中
            uploadAction: "/api/minio/upload/permanent",
            showSelectBucket:false, //是否需要选择桶
            formFile:null,
        }
    },
    methods: {
        clearFile(){
            this.file = {}
            this.defaultList = []
        },
        clearFileInList(){
            this.file = {}
            this.$emit('clearFile')
        },
        showDefaultList(file){
            if(this.fileType=='images'){
                this.defaultList = [];
                this.file = {...file}
            }else{
                if(file){
                    this.file = {...file};
                    this.defaultList = [{
                        name:file.fileName||'文件',
                        url:file.filePath
                    }]
                }else{
                    this.file = {};
                    this.defaultList = []
                }

            }
        },
        chooseImg(params) {
            let template = this.list.find(item => item.id === params.row.id)
            if (params.row.isUsed) {
                if (template) {
                    this.$set(template, 'isUsed', false)
                }
                if (this.fileType !== 'images') {
                    this.$emit('del-item-fildId', params.row.id)
                } else {
                    this.delImge()
                }
                return
            }
            if (template) {
                if (this.isSingle) { // 单选模式，需要将其他的选中项全部设置为未选
                    this.list.forEach(item => this.$set(item, 'isUsed', false))
                }
                this.$set(template, 'isUsed', true)
            }
            this.$emit('upload-success', {
                fisleId: params.row.id,
                filePath: params.row.path,
                fileName: params.row.originName
            })
        },
        checkInfo(params) {
            let path = params.row.path;
            if(params.row.originName.endsWith('.md')){
                let href = this.$router.resolve({
                    name:'mdPreview',
                    query:{
                        path:path,
                        name:params.row.originName
                    }
                }).href;
                window.openTrain(href,'_blank')
            }else{
                window.openTrain(`/api/minio/filePreview?path=${path}`);
            }
        },
        handlePublic(val){
            let obj = {
                text:'',
                color:'#8d95a6'
            }
            switch (val){
                case 'person':
                case 0:
                case '0':
                    return obj = {
                        text:'个人',
                        color:'rgb(255, 165, 0)',
                    }
                    break;
                case 'company':
                case 1:
                case '1':
                    return obj = {
                        text:'单位',
                        color:'rgb(50, 205, 50)',
                    }
                    break;
                case 'system':
                case 2:
                case '2':
                    return obj = {
                        text:'系统',
                        color:'rgb(65, 105, 225)',
                    }
                    break;
              case 'range':
              case 3:
              case '3':
                return obj = {
                  text:'平台',
                  color:'#ff61f4',
                }
                break;
            }
        },
        handleImage(logo) {
            let src = ''
            if(logo) {
                if(logo.indexOf('Learn') > -1) {
                    src = logo
                } else {
                    src = `/Learn/${logo}`
                }
            } else {
                src = this.defaultImg
            }
            return src
        },
        getShowColumns() {
            if(this.fileType != 'images') {
                return this.columns.filter(col => col.key != 'path');
            } else {
                return this.columns;
            }
        },
        refresh() {
            this.query.pageIndex = 1
            this.originName = ''
            this.getMinioList()
        },
        // 设置高度
        setStyle() {
            window.fullHeight = document.documentElement.clientHeight;
            window.fullWidth = document.documentElement.clientWidth;
            this.fullHeight = window.fullHeight;
            this.fullWidth = window.fullWidth;
            this.contentHei = this.fullHeight - 60 - 21 + 'px' // 80是头部高度  60是上下padding
            this.setUserTableHei = this.fullHeight - 212
            this.query.pageSize = Math.floor(this.setUserTableHei / 50) - 1
        },
        getMinioList(pageIndex) {
            this.query.pageIndex = pageIndex || 1
            this.loadingList = true
            getFilesData(this.query, {
                bucket: this.fileType,
                originName: this.originName,
                visibility: 'share'
            }).then(({ data = {} }) => {
                let { code, message } = data
                if (code !== 1) {
                    this.$Message.warning(message)
                    this.list = []
                    this.total = 0
                    return
                }
                data = data.data || {}
                this.list = (data.list || []).map(item => {
                    item.isUsed = this.filePaths.includes(item.path)
                    return item
                })
                this.total = data.total
            }).finally(() => {
                this.loadingList = false
            })
        },
        showDrawer() {
            this.refresh()
            this.drawerValue = true
            this.getMinioList()
        },
        delItem(id) {
            this.$emit('del-item', id)
        },
        delImge(path) {
            this.$emit('del-image', path)
        },
        // 上传图片成功后的回调函数，获取图片上传后的保存的位置，用于回显图片
        getFileUrl(res) {
            if (res.code == 1) {
                this.file = {
                    fileId: res.info.id,
                    filePath: res.data,
                    fileName: res.info.originalName
                }

                this.$refs.uploadFile.clearFiles();
                if(this.fileType=='images'){
                    this.defaultList=[]
                }else{
                    this.defaultList = [{
                        name:this.file.fileName,
                        url:this.file.filePath
                    }];
                }
                this.$emit('upload-success',this.file)
            } else {
                let message = res.message||'文件上传失败'
                this.defaultList = [];
                this.$Message.error(message)
            }
        },
        getFileName (name) {
            return name.substring(0, name.lastIndexOf("."))
        },
        async handleUploadIcon(file){
            this.speed = 0;
            this.loaded = 0;
            this.progress = 0;
            this.isUpdataing = true
            this.onlyFileName = file.name + '_' + new Date().getTime();
            if (file) {
                if (file.size > 1024 * 1024) {
                    this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
                } else {
                    this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
                }
                //验证名称
                if(file.name){
                    let name = this.getFileName(file.name);
                    let reg = new RegExp("^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$");
                    if (!reg.test(name) || name.length > 64) {
                        return new Promise((resolve,reject)=>{
                            this.$Message.warning('文件名称只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符')
                        reject();

                        })

                    }
                }
            }
            let exceededNum=file.name.lastIndexOf(".");
            let exceededStr=file.name.substring(exceededNum+1,file.name.length).trim().toLowerCase();
            if(exceededStr && this.formatArr.indexOf(exceededStr)>-1){
                // 什么都不需要做
                //只显示当前上传文件
            }else{
                return new Promise((resolve,reject)=>{
                    this.$Message.warning(`不支持当前文件类型,请上传${this.formatArr.toString()}格式`);
                    reject();
                    })
            }
            if(this.customApi){
                let formData = new FormData();
                formData.append('file',file);
                if(this.cusdomPassObj){
                    for(let key in this.cusdomPassObj){
                        formData.append(key,this.cusdomPassObj[key])
                    }
                }
                // formData.append('testProjectId',this.uploadParams.testProjectId);
                // formData.append('testObjectId',this.uploadParams.testObjectId);
                // formData.append('bcProjectId',this.uploadParams.bcProjectId);
               return await this.customApi(formData).then(res=>{
                   if(res.code==1){
                    let flag = false;
                    let obj = {}
                    if(this.cusdomCallback&&typeof this.cusdomCallback=='function'){
                        //此处回调需要返回一个继续往下走的回调值{flag:true,message:'dddd'}
                        obj = this.cusdomCallback(res)
                    }
                    flag = obj.flag;
                    let message = obj.message||'检测未通过'
                    return new Promise((resolve,reject)=>{
                        if(!flag){
                            this.$Message.info(message);
                            reject()
                        }else{
                            resolve()
                        }
                    })
                   }else{
                    this.$Message.error(res.message)
                    return new Promise((resolve,reject)=>{
                        reject()
                    })
                   }
                })
            }
        },
    }
}
</script>

<style scoped>
.imageShow{
    display: flex;
    justify-content: space-between;
}
.imageShow:hover{
    background-color: var(--select-bgcolor);
}
.imageDelIcon{
    padding-right: 10px;
    opacity:0;
}
.imageShow:hover .imageDelIcon{
    opacity:1
}
.choose-btn {
    float: left;
    margin: 1px 6px 0 0;
}

.file-list {
    max-height: 132px;
    overflow: auto;
    width: 100%;
}

.file-list>.content {
    display: flex;
    align-items: center;
    margin: 6px;
    justify-content: space-between;
}

.file-list .file-name {
    flex: 1;
    margin-left: 6px;
}

.file-list /deep/ button {
    border: none !important;
}

.file-list /deep/ button i {
    font-size: 16px;
    color: #ed4014;
}
</style>
